﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports Forecast.Logica.Enumeradores
Imports Forecast.Logica.Servicios
Imports Forecast.Logica.Modelos

Public Class AgregarForecast
    Inherits System.Web.UI.UserControl
    Private Shared _servUsuarios As ServUsuarios
    Private Shared _servClientes As ServClientes
    Private Shared _servSegmentoPL As ServSegmentPL
    Private Shared _servServProduct As ServProduct
    Private Shared _ServForecast As ServForecast
    Private Shared _ServPeriod As ServPeriod
    Private Shared _ServCurrency As ServCurrency
    Private Shared _servUOM As ServUOM
    Private Shared _ServPriceSale As ServPriceSale

    Public Usuario As Usuario
    Public Clientes As Clientes
    Public TBProducto As System.Data.DataTable
    Public TBProductoIng As System.Data.DataTable
    Public Sub Mostrar()
        '  mpeAgregarGasto.Show()
    End Sub
    Public Sub Cerrar()
        Session("MostrarListado") = True
        '  mpeAgregarGasto.Hide()
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Usuario = Session("usuario")
        If Not Page.IsPostBack Then

            CargarCombos(0)
            ' CargarProductoDeForecast() -------------------------------OCULTADO
            TBFiltro.Visible = False
            TBDetalleForecast.Visible = False
            TBFormIngModForescast.Visible = False
            lblMensajeIngreso.Visible = False

            TxtNombreCliente.Visible = False
            lblNombreCliente.Visible = False

            DrCurrencyUP.Visible = False
            TxtUnitPriceUP.Visible = False
            LblUnitPrice.Visible = False
            DrUOM.Visible = False
            TxtUOMIng.Visible = True
            LblProductName.Visible = False
            TxtProductName.Visible = False
            '  upAgregarGasto.Visible = False
        Else
            lblMensajeIngreso.Visible = False
            MensajeExistencia.Visible = False

            If Panel1.Visible = False Then
                BtnGuardarForeCast.Visible = False
                BtnGuardarForeCast2.Visible = True
                BtnCancelarForeCast.Visible = True
            End If


            '  upAgregarGasto.Visible = True
        End If
    End Sub
    Protected Sub BtnGuardarForeCast_Click(sender As Object, e As EventArgs) Handles BtnGuardarForeCast.Click
        Usuario = Session("usuario")
        Dim SiError As Boolean
        SiError = ValidarCampos()
        If SiError = True Then
            Exit Sub
        End If

        Dim ModForecast = TransformarForeCast()
        _ServForecast = New ServForecast()

        Dim ExisteForecast = ConsultarForecastExistente() ' _ServForecast.VerificarExistenciaForecast(ModForecast)
        If ExisteForecast.Rows.Count > 0 And LblTitulo.Text = "Add Forecast" Then
            If ExisteForecast.Rows(0).Item("IdUsuario") = Usuario.IdUsuario Then
                lblMsgExiste.Text = "El Forecast del Cliente y Producto seleccionado ya fueron ingresados con anterioridad desea abrirlo."
                btnCargarForecastSI.Visible = True
                btncargarForecastNO.Visible = True
            Else
                lblMsgExiste.Text = "El Forecast del Cliente y Producto seleccionado ya fue ingresado por " & ExisteForecast.Rows(0).Item("NameUser")
                btnCargarForecastSI.Visible = False
                btncargarForecastNO.Visible = False
            End If

            MensajeExistencia.Visible = True
            SiError = True
            BtnGuardarForeCast.Visible = False
            BtnCancelarForeCast.Visible = False
        End If

        If SiError = True Then
            Exit Sub
        End If

        _ServForecast.GuardarForecast(ModForecast)
        If ModForecast.IdForecast <> 0 Then
            ' CargarProductoDeForecast() -------------------------------OCULTADO

            CargarForescat(ModForecast.IdCustomer, ModForecast.IdProduct)
            Session("ActualizarListado") = True
            TBDetalleForecast.Visible = True
            TBFormIngModForescast.Visible = False
            lblMensajeIngreso.Visible = True
        End If

        '-----------------------------------------------------
       


    End Sub
    Private Function ValidarCampos() As Boolean
        ' LimpiarErrores
        DrPeriodo.CssClass = ""
        DrClienteIng.CssClass = ""
        DrSegmentoPLIng.CssClass = ""
        DrProductoIng.CssClass = ""
        TxtVolumen.CssClass = ""

        Dim SiError As Boolean
        SiError = False

        If DrPeriodo.SelectedValue = 0 Then
            DrPeriodo.CssClass = "error"
            SiError = True
        End If
        If DrClienteIng.SelectedValue = 0 Then
            DrClienteIng.CssClass = "error"
            SiError = True
        End If
        If DrSegmentoPLIng.SelectedValue = 0 Then
            DrSegmentoPLIng.CssClass = "error"
            SiError = True
        End If
        If DrProductoIng.Items.Count > 0 Then
            If DrProductoIng.SelectedValue = 0 Then
                DrProductoIng.CssClass = "error"
                SiError = True
            End If
        Else
            DrProductoIng.CssClass = "error"
            SiError = True
        End If

        If TxtVolumen.Text.Trim() = "" Then
            TxtVolumen.CssClass = "error"
            SiError = True
        End If

        If TxtVolumen.Text.Trim() <> "" Then
            If Not IsNumeric(TxtVolumen.Text.Trim) Then
                TxtVolumen.CssClass = "error"
                SiError = True
            Else
                If TxtVolumen.Text.Trim() < 0 Then
                    TxtVolumen.CssClass = "error"
                    SiError = True
                End If
            End If

        End If

        If DrClienteIng.SelectedValue = 99999999 And Trim(TxtNombreCliente.Text) = "" Then
            TxtNombreCliente.CssClass = "error"
            SiError = True
        End If
        If DrClienteIng.SelectedValue = 99999999 And Trim(TxtUnitPriceUP.Text) = "" Then
            If Not IsNumeric(TxtUnitPriceUP.Text.Trim) Then
                TxtUnitPriceUP.CssClass = "error"
                SiError = True
            Else
                If TxtUnitPriceUP.Text.Trim() < 0 Then
                    TxtUnitPriceUP.CssClass = "error"
                    SiError = True
                End If
            End If
        End If
        If DrClienteIng.SelectedValue = 99999999 And DrCurrencyUP.SelectedValue = "0" Then
            DrCurrencyUP.CssClass = "error"
            SiError = True
        End If

        If DrProductoIng.SelectedValue = 99999999 And Trim(TxtProductName.Text) = "" Then
            TxtProductName.CssClass = "error"
            SiError = True
        End If
        If DrProductoIng.SelectedValue = 99999999 And DrUOM.SelectedValue = "0" Then
            DrUOM.CssClass = "error"
            SiError = True
        End If


        Return SiError
    End Function
    Private Function TransformarForeCast() As ModForecast
        Dim ModForecast = New ModForecast()
        If Session("IdForecast") <> 0 Then
            ModForecast.IdForecast = Session("IdForecast")
        End If

        ModForecast.IdPeriod = DrPeriodo.SelectedValue
        ModForecast.IdCustomer = DrClienteIng.SelectedValue
        ModForecast.IdUsuario = Usuario.IdUsuario
        ModForecast.IdProduct = DrProductoIng.SelectedValue
        ModForecast.IdUOM = 0
        ModForecast.Volume = TxtVolumen.Text
        ModForecast.ValueProduct = TxtUnitPriceUP.Text
        ModForecast.Currency = DrCurrencyUP.SelectedValue
        If ChSpecial.Checked = True Then
            ModForecast.Special = True
        Else
            ModForecast.Special = False
        End If

        If ModForecast.IdCustomer = 99999999 Then
        ModForecast.NameCustomerOther = TxtNombreCliente.Text
        End If
        ModForecast.IdEntityF = Usuario.IdEntityF
        ModForecast.IdSegment = DrSegmentoPLIng.SelectedValue

        If ModForecast.IdProduct = 99999999 Then
            ModForecast.NameProductOther = TxtProductName.Text
        End If

        Return ModForecast

    End Function
    Private Function CargaParamBusqueda() As BusForecast

        Dim BusForecast = New BusForecast()
        BusForecast.IdCustomer = DrClientesB.SelectedValue
        BusForecast.IdUOM = DrUOMB.SelectedValue
        If DrProductoB.SelectedValue <> "" Then
            BusForecast.IdProduct = CInt(DrProductoB.SelectedValue)
        End If
        BusForecast.IdSegmento = DrSegmentoPLB.SelectedValue
        BusForecast.IdProductLine = DrProductLineB.SelectedValue
        BusForecast.CodCustomer = TxtCodClienteB.Text
        Return BusForecast

    End Function
    Public Sub SoloIngreso()
        upAgregarGasto.Visible = True
        TBCabezera.Visible = False
        Panel1.Visible = False
        TBDetalleForecast.Visible = False
        BtnGuardarForeCast.Visible = False
        BtnGuardarForeCast2.Visible = True

        NuevoForeCast()
        '--- Limpiar productos
        cargarProductos(0, 9999, 0)

        DrClienteIng.Enabled = True
        DrSegmentoPLIng.Enabled = True

        DrClienteIng.Visible = True
        DrSegmentoPLIng.Visible = True
        LblCustomerING.Visible = True
        lblSegmentPLING.Visible = True
        lblPrecioCU.Text = ""
        lblPrecioCU.Visible = False
        lblMensajeIngreso.Visible = False

        TxtNombreCliente.Visible = False
        lblNombreCliente.Visible = False
        DrCurrencyUP.Visible = False
        TxtUnitPriceUP.Visible = False
        LblUnitPrice.Visible = False
        DrUOM.Visible = False
        TxtUOMIng.Visible = True
        LblProductName.Visible = False
        TxtProductName.Visible = False
        ChSpecial.Enabled = True
        ChSpecial.Checked = False
        DrClienteIng.Focus()
        Mostrar()
    End Sub
    Public Sub CargarProductoDeForecast(_BusForecast As BusForecast)
        _servServProduct = New ServProduct()
        'Dim _BusForecast = CargaParamBusqueda()
        Dim objDT As System.Data.DataTable
        Dim TBProductoDeForecast = _servServProduct.SearchProduct_DeForecast(Usuario.IdEntityF, Usuario.IdUsuario, _BusForecast)  '# DEJAR AÑO PARAMETRIZADO
        Dim objDR As System.Data.DataRow
        Dim Special As Boolean

        objDT = New System.Data.DataTable("GrProductDeForeCast")
        objDT.Columns.Add("ID", GetType(Integer))
        objDT.Columns("ID").AutoIncrement = True
        objDT.Columns("ID").AutoIncrementSeed = 1
        objDT.Columns.Add("CodCliente", GetType(String))
        objDT.Columns.Add("DesSegment", GetType(String))
        objDT.Columns.Add("DesProductLine", GetType(String))
        objDT.Columns.Add("DesProduct", GetType(String))
        objDT.Columns.Add("CodUOM", GetType(String))
        objDR = objDT.NewRow

        If TBProductoDeForecast.Rows.Count > 0 Then
            For k = 0 To TBProductoDeForecast.Rows.Count - 1 Step 1
                objDR = objDT.NewRow
                objDR("CodCliente") = TBProductoDeForecast.Rows(k).Item("CodCliente")
                objDR("DesSegment") = TBProductoDeForecast.Rows(k).Item("DesSegment")
                objDR("DesProductLine") = TBProductoDeForecast.Rows(k).Item("DesProductLine")
                objDR("DesProduct") = TBProductoDeForecast.Rows(k).Item("DesProduct")
                objDR("CodUOM") = TBProductoDeForecast.Rows(k).Item("CodUOM")
                objDT.Rows.Add(objDR)

                If k = 0 Then
                    txtCodCliente_.Text = TBProductoDeForecast.Rows(k).Item("CodCliente")
                    TxtCliente_.Text = TBProductoDeForecast.Rows(k).Item("NameCustomer")
                    TxtSegmento_.Text = TBProductoDeForecast.Rows(k).Item("DesSegment")
                    txtProductLine_.Text = TBProductoDeForecast.Rows(k).Item("DesProductLine")
                    Special = TBProductoDeForecast.Rows(k).Item("Special")
                End If

            Next
        End If
        Session("ProductDeForeCast") = TBProductoDeForecast
        GrProductDeForeCast.DataSource = objDT
        GrProductDeForeCast.DataBind()

        TBCabezera.Visible = True
        Panel1.Visible = True
        BtnGuardarForeCast.Visible = True
        BtnGuardarForeCast2.Visible = False
        TBDetalleForecast.Visible = False
        TBFormIngModForescast.Visible = False
        lblMensajeIngreso.Visible = False

        ChSpecial.Enabled = False
        If Special = True Then
            ChSpecial.Checked = True
        Else
            ChSpecial.Checked = False
        End If

        Mostrar()
    End Sub
    Public Sub CargarCombos(TipoCarga As Integer)
        If TipoCarga = 1 Then
            'MODIFICACION DE FORESCAST
            'CLIENTE
            '_servClientes = New ServClientes()
            'DrClientes.DataTextField = "Name"
            'DrClientes.DataValueField = "IdCustomer"
            'DrClientes.DataSource = _servClientes.SearchCliente(Usuario.IdEntityF)
            'DrClientes.DataBind()

            ''SegementPL
            ''_servSegmentoPL = New ServSegmentPL()
            ''DrSegmentoPL.DataTextField = "DesSegmentPL"
            ''DrSegmentoPL.DataValueField = "IdSegmentPL"
            ''DrSegmentoPL.DataSource = _servSegmentoPL.SearchSegmentPL(Usuario.IdEntityF, 2013)  '# DEJAR AÑO PARAMETRIZADO
            ''DrSegmentoPL.DataBind()

            'If DrClientes.SelectedValue > 0 Then
            '    cargarSegmentoPL(1, DrClientes.SelectedValue)
            '    cargarProductos(1, DrSegmentoPL.SelectedValue, DrClientes.SelectedValue)
            'End If



        Else
            'INGRESO DE NUEVO FORECAST o MODIFICACION
            'CLIENTE
            _servClientes = New ServClientes()
            Dim ListClientes = _servClientes.SearchCliente(Usuario.IdEntityF)
            DrClienteIng.DataTextField = "Name"
            DrClienteIng.DataValueField = "IdCustomer"
            DrClienteIng.DataSource = ListClientes
            DrClienteIng.DataBind()

            DrClientesB.DataTextField = "Name"
            DrClientesB.DataValueField = "IdCustomer"
            DrClientesB.DataSource = ListClientes
            DrClientesB.DataBind()


            ''SegementPL
            cargarSegmentoPL(0, DrClienteIng.SelectedValue)

            '_servSegmentoPL = New ServSegmentPL()
            'Dim ListSegmentoPL = _servSegmentoPL.SearchSegmentPL(Usuario.IdEntityF, 2013)  '# DEJAR AÑO PARAMETRIZADO
            'DrSegmentoPLIng.DataTextField = "DesSegmentPL"
            'DrSegmentoPLIng.DataValueField = "IdSegmentPL"
            'DrSegmentoPLIng.DataSource = ListSegmentoPL
            'DrSegmentoPLIng.DataBind()


            'Monedas
            _ServCurrency = New ServCurrency()
            Dim ListCurrency = _ServCurrency.SearchCurrency(Usuario.IdEntityF)
            DrCurrencyUP.DataTextField = "DesCurrency"
            DrCurrencyUP.DataValueField = "CodCurrency"
            DrCurrencyUP.DataSource = ListCurrency
            DrCurrencyUP.DataBind()


            'UNIDADES DE MEDIDAS UOM
            _servUOM = New ServUOM()
            Dim ListUOMEntity = _servUOM.SearchUOM_PorEntity(Usuario.IdEntityF)
            DrUOM.DataTextField = "DesUOM"
            DrUOM.DataValueField = "IdUOM"
            DrUOM.DataSource = ListUOMEntity
            DrUOM.DataBind()


            'Periodo
            _ServPeriod = New ServPeriod()
            Dim ListPeriod = _ServPeriod.SearchPeriod(Usuario.IdEntityF)
            DrPeriodo.DataTextField = "Period"
            DrPeriodo.DataValueField = "IdPeriod"
            DrPeriodo.DataSource = ListPeriod
            DrPeriodo.DataBind()

            'Cargar Producto por Segmento
            If (DrSegmentoPLIng.SelectedValue IsNot Nothing) And (DrSegmentoPLIng.SelectedValue > 0) Then
                cargarProductos(0, DrSegmentoPLIng.SelectedValue, DrClienteIng.SelectedValue)
            End If

            'Producto de Busqueda
            _servServProduct = New ServProduct()
            Dim ListProducto = _servServProduct.SearchProduct(Usuario.IdEntityF, 0, DrClienteIng.SelectedValue)  '# DEJAR AÑO PARAMETRIZADO

            DrProductoB.DataTextField = "CodDesproduct"
            DrProductoB.DataValueField = "IdProduct"
            DrProductoB.DataSource = ListProducto
            DrProductoB.DataBind()

            'Cargar Solo Segemnto en Busqueda
            _servSegmentoPL = New ServSegmentPL()
            Dim ListSegmento = _servSegmentoPL.SearchSegmentPL_SoloSegmento(Usuario.IdEntityF)
            DrSegmentoPLB.DataTextField = "desSegment"
            DrSegmentoPLB.DataValueField = "IdSegment"
            DrSegmentoPLB.DataSource = ListSegmento
            DrSegmentoPLB.DataBind()

            'Cargar Solo ProductLine
            Dim ListProductLine = _servSegmentoPL.SearchSegmentPL_SoloProductLine(Usuario.IdEntityF)
            DrProductLineB.DataTextField = "DesProductLine"
            DrProductLineB.DataValueField = "IdProductLine"
            DrProductLineB.DataSource = ListProductLine
            DrProductLineB.DataBind()

            'Cargar UOM
            _servUOM = New ServUOM()
            Dim ListUOM = _servUOM.SearchUOM()
            DrUOMB.DataTextField = "DesUOM"
            DrUOMB.DataValueField = "IdUOM"
            DrUOMB.DataSource = ListUOM
            DrUOMB.DataBind()
        End If

    End Sub

    Public Sub cargarProductos(TipoCarga As Integer, SegmentoPL As Integer, IdCliente As Integer)
        'SegementPL

        If TipoCarga = 1 Then   'MODIFICACION DE FORESCAST
            _servServProduct = New ServProduct()
            TBProducto = _servServProduct.SearchProduct(Usuario.IdEntityF, SegmentoPL, IdCliente)  '# DEJAR AÑO PARAMETRIZADO

            Session("TBProducto") = TBProducto
            DrProducto.DataTextField = "CodDesproduct"
            DrProducto.DataValueField = "IdProduct"
            DrProducto.DataSource = TBProducto
            DrProducto.DataBind()

            Dim index = DrProducto.SelectedIndex
            If index > -1 Then
                txtIdUOM.Text = TBProducto.Rows(index).Item("DesUOM")
                TxtUOM.Text = TBProducto.Rows(index).Item("DesUOM")
            End If
        Else    ' INGRESO DE NUEVO FORECAST
            _servServProduct = New ServProduct()
            TBProducto = _servServProduct.SearchProduct(Usuario.IdEntityF, SegmentoPL, IdCliente)  '# DEJAR AÑO PARAMETRIZADO

            Session("TBProductoIng") = TBProducto
            DrProductoIng.DataTextField = "CodDesproduct"
            DrProductoIng.DataValueField = "IdProduct"
            DrProductoIng.DataSource = TBProducto
            DrProductoIng.DataBind()

            Dim index = DrProductoIng.SelectedIndex
            If index > -1 Then
                txtIdUOM.Text = TBProducto.Rows(index).Item("DesUOM")
                TxtUOMIng.Text = TBProducto.Rows(index).Item("DesUOM")
            End If
        End If


    End Sub

    'Protected Sub DrSegmentoPL_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DrSegmentoPL.SelectedIndexChanged
    '    cargarProductos(1, DrSegmentoPL.SelectedValue, DrClientes.SelectedValue)
    'End Sub

    Protected Sub DrSegmentoPLIng_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DrSegmentoPLIng.SelectedIndexChanged
        cargarProductos(0, DrSegmentoPLIng.SelectedValue, DrClienteIng.SelectedValue)
    End Sub

    Protected Sub DrProducto_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DrProducto.SelectedIndexChanged
        Dim index = DrProducto.SelectedIndex
        TBProducto = Session("TBProducto")

        If index > -1 Then
            txtIdUOM.Text = TBProducto.Rows(index).Item("IdUOM")
            TxtUOM.Text = TBProducto.Rows(index).Item("DesUOM")
        End If

    End Sub
    Protected Sub DrProductoIng_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DrProductoIng.SelectedIndexChanged
        Dim index = DrProductoIng.SelectedIndex
        TBProductoIng = Session("TBProductoIng")

        If index > -1 Then
            txtIdUOM.Text = TBProductoIng.Rows(index).Item("IdUOM")
            TxtUOMIng.Text = TBProductoIng.Rows(index).Item("DesUOM")
        End If

        If DrProductoIng.SelectedValue = 99999999 Then
            LblProductName.Visible = True
            TxtProductName.Visible = True

            TxtUOMIng.Visible = False
            DrUOM.Visible = True
        Else
            LblProductName.Visible = False
            TxtProductName.Visible = False

            TxtUOMIng.Visible = True
            DrUOM.Visible = False

        End If

        'Dim InfoPrice As String
        '_ServPriceSale = New ServPriceSale
        'Dim TBPriceSale = _ServPriceSale.SearchPriceSale(DrClienteIng.SelectedValue, DrProductoIng.SelectedValue)
        'InfoPrice = "Unit Price: " & TBPriceSale.Rows(0).Item("Value") & " " & TBPriceSale.Rows(0).Item("Currency")
        'lblPrecioCU.Text = InfoPrice
        'lblPrecioCU.Visible = True
    End Sub
    Public Function CargarInfoPeriodos(IDProduct As Integer, IdCustomer As Integer, IdSegmentPL As Integer, SiActivo As Integer) As DataTable
        _ServForecast = New ServForecast()
        Dim objDT As System.Data.DataTable
        Dim TBProductoDeForecast = _ServForecast.Search_InfoPeriodos(IDProduct, IdCustomer, IdSegmentPL, SiActivo)  '# DEJAR PARAMETRIZADO
        Dim objDR As System.Data.DataRow

        objDT = New System.Data.DataTable("GrPeriod")
        objDT.Columns.Add("ID", GetType(Integer))
        objDT.Columns("ID").AutoIncrement = True
        objDT.Columns("ID").AutoIncrementSeed = 1
        objDT.Columns.Add("IdForecast", GetType(Integer))
        objDT.Columns.Add("IdCustomer", GetType(Integer))
        objDT.Columns.Add("IdProduct", GetType(Integer))
        objDT.Columns.Add("IdSegmentPL", GetType(Integer))
        objDT.Columns.Add("IdPeriod", GetType(Integer))
        objDT.Columns.Add("Codigo", GetType(String))
        objDT.Columns.Add("IdEntityF", GetType(Integer))
        objDT.Columns.Add("Period", GetType(String))
        objDT.Columns.Add("DesUOM", GetType(String))
        objDT.Columns.Add("Volume", GetType(String))
        objDT.Columns.Add("DesProduct", GetType(String))
        objDT.Columns.Add("ValuePC", GetType(String))
        objDT.Columns.Add("CurrencyPC", GetType(String))
        objDT.Columns.Add("ValuesSP", GetType(String))
        objDT.Columns.Add("CurrencySP", GetType(String))
        objDR = objDT.NewRow

        If TBProductoDeForecast.Rows.Count > 0 Then
            For k = 0 To TBProductoDeForecast.Rows.Count - 1 Step 1
                objDR = objDT.NewRow
                objDR("IdForecast") = TBProductoDeForecast.Rows(k).Item("IdForecast")
                objDR("IdCustomer") = TBProductoDeForecast.Rows(k).Item("IdCustomer")
                objDR("IdProduct") = TBProductoDeForecast.Rows(k).Item("IdProduct")
                objDR("IdSegmentPL") = TBProductoDeForecast.Rows(k).Item("IdSegmentPL")
                objDR("IdPeriod") = TBProductoDeForecast.Rows(k).Item("IdPeriod")
                objDR("Codigo") = TBProductoDeForecast.Rows(k).Item("Codigo")
                objDR("IdEntityF") = TBProductoDeForecast.Rows(k).Item("IdEntityF")
                objDR("Period") = TBProductoDeForecast.Rows(k).Item("Period")
                objDR("Volume") = FormatNumber(TBProductoDeForecast.Rows(k).Item("Volume"), 2)
                objDR("DesUOM") = TBProductoDeForecast.Rows(k).Item("DesUOM")
                objDR("DesProduct") = TBProductoDeForecast.Rows(k).Item("DesProduct")
                objDR("ValuePC") = FormatNumber(TBProductoDeForecast.Rows(k).Item("ValuePC"), 2)
                objDR("CurrencyPC") = TBProductoDeForecast.Rows(k).Item("CurrencyPC")
                objDR("ValuesSP") = FormatNumber(TBProductoDeForecast.Rows(k).Item("ValuesSP"), 2)
                objDR("CurrencySP") = TBProductoDeForecast.Rows(k).Item("CurrencySP")
                objDT.Rows.Add(objDR)
            Next
        End If
        Return objDT



    End Function

    Protected Sub GrProductDeForeCast_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GrProductDeForeCast.RowCommand
        If e.CommandName = "Select" Then
                Dim index As Integer = Convert.ToInt32(e.CommandArgument)
                Dim IdCustomer, IdProduct As Integer
                IdCustomer = Session("ProductDeForeCast").rows(index).Item("IdCustomer").ToString
                IdProduct = Session("ProductDeForeCast").rows(index).Item("IdProduct").ToString
                CargarForescat(IdCustomer, IdProduct)

            End If
    End Sub
    Private Sub CargarForescat(Customer As Integer, Product As Integer)
        _ServForecast = New ServForecast()
        Dim DetForecast = _ServForecast.Read_Forecast(Customer, Product)
        Dim IdProduct, IdCustomer, IdSegmentPL, IdUOM, IdSegment, IdProductLine As Integer
        Dim DesUOM, CodCliente As String
        Dim Special As Boolean

        If DetForecast.Rows.Count > 0 Then
            IdCustomer = DetForecast.Rows(0).Item("IdCustomer")
            IdSegmentPL = DetForecast.Rows(0).Item("IdSegmentPL")
            IdProduct = DetForecast.Rows(0).Item("IdProduct")
            IdSegment = DetForecast.Rows(0).Item("IdSegment")
            IdProductLine = DetForecast.Rows(0).Item("IdProductLine")
            IdUOM = DetForecast.Rows(0).Item("IdUOM")
            DesUOM = DetForecast.Rows(0).Item("DesUOM").ToString
            CodCliente = DetForecast.Rows(0).Item("CodCliente").ToString
            Special = DetForecast.Rows(0).Item("special").ToString
        End If

        Dim _BusForecast = CargaParamBusqueda(IdCustomer, IdSegment, IdProductLine)
        CargarProductoDeForecast(_BusForecast)

        CargarCombos(0)
        cargarSegmentoPL(1, IdCustomer)
        cargarProductos(1, IdSegmentPL, IdCustomer)

        txtIdUOM.Text = IdUOM
        TxtUOM.Text = DesUOM 'Session("ProductDeForeCast").rows(index).Item("DesUOM").ToString
        'txtCodCliente.Text = CodCliente
        'DrClientes.SelectedValue = IdCustomer
        'DrSegmentoPL.SelectedValue = IdSegmentPL
        DrProducto.SelectedValue = IdProduct
        ChSpecial.Enabled = False
        If Special = True Then
            ChSpecial.Checked = True
        Else
            ChSpecial.Checked = False
        End If

        Dim GRInactivas = CargarInfoPeriodos(IdProduct, IdCustomer, IdSegmentPL, 0)
        GrPeriodInactivo.DataSource = GRInactivas
        GrPeriodInactivo.DataBind()

        Dim GRActiva = CargarInfoPeriodos(IdProduct, IdCustomer, IdSegmentPL, 1)
        Session("GRActiva") = GRActiva
        GrPeriodActivo.DataSource = GRActiva
        GrPeriodActivo.DataBind()

        'DrClientes.Enabled = False
        'DrSegmentoPL.Enabled = False
        DrProducto.Enabled = False


        TBDetalleForecast.Visible = True
        TBFormIngModForescast.Visible = False
    End Sub

 

    Protected Sub btnIngresarForescast_Click(sender As Object, e As EventArgs) Handles btnIngresarForescast.Click
        NuevoForeCast()

        '    Session("ProductDeForeCast")
        TBProducto = Session("ProductDeForeCast")

        If TBProducto.Rows.Count > -1 Then
            DrClienteIng.SelectedValue = TBProducto.Rows(0).Item("IdCustomer")
            cargarSegmentoPL(0, DrClienteIng.SelectedValue)
            DrSegmentoPLIng.SelectedValue = TBProducto.Rows(0).Item("IdSegmentPL")
            'Cargar Producto por Segmento
            If (DrSegmentoPLIng.SelectedValue IsNot Nothing) And (DrSegmentoPLIng.SelectedValue > 0) Then
                cargarProductos(0, DrSegmentoPLIng.SelectedValue, DrClienteIng.SelectedValue)
            End If

            DrClienteIng.Enabled = False
            DrSegmentoPLIng.Enabled = False

            DrClienteIng.Visible = False
            DrSegmentoPLIng.Visible = False
            LblCustomerING.Visible = False
            lblSegmentPLING.Visible = False
            lblPrecioCU.Text = ""
        End If

    End Sub
    Public Sub NuevoForeCast()
        Session("IdForecast") = 0

        CargarCombos(0)
        TBFormIngModForescast.Visible = True
        TBDetalleForecast.Visible = False

        DrClienteIng.Enabled = True
        DrSegmentoPLIng.Enabled = True
        DrProductoIng.Enabled = True
        DrPeriodo.Enabled = True
        TxtUOMIng.Enabled = False
        txtIdUOM.Text = ""
        TxtUOMIng.Text = ""
        TxtVolumen.Text = ""
        DrProductoIng.Focus()
        DrProductoIng.SelectedValue = 0
        LblTitulo.Text = "Add Forecast"
    End Sub
    Protected Sub GrPeriodActivo_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GrPeriodActivo.RowCommand
        If e.CommandName = "Editar" Then

            Dim index As Integer = Convert.ToInt32(e.CommandArgument)
            Dim IdProduct, IdCustomer, IdSegmentPL, IdPeriod As Integer
            Dim Volumen As String
            Session("IdForecast") = Session("GRActiva").rows(index).Item("IdForecast").ToString
            IdCustomer = Session("GRActiva").rows(index).Item("IdCustomer").ToString
            IdSegmentPL = Session("GRActiva").rows(index).Item("IdSegmentPL").ToString
            IdProduct = Session("GRActiva").rows(index).Item("IdProduct").ToString
            IdPeriod = Session("GRActiva").rows(index).Item("IdPeriod").ToString
            Volumen = Session("GRActiva").rows(index).Item("Volume").ToString

            ' CargarCombos(0)
            cargarSegmentoPL(0, IdCustomer)
            cargarProductos(0, IdSegmentPL, IdCustomer)

            DrClienteIng.SelectedValue = IdCustomer
            DrSegmentoPLIng.SelectedValue = IdSegmentPL
            DrProductoIng.SelectedValue = IdProduct
            DrPeriodo.SelectedValue = IdPeriod
            TxtVolumen.Text = Volumen
            TxtUOMIng.Text = TxtUOM.Text
            LblTitulo.Text = "Change Forecast"

            DrClienteIng.Enabled = False
            DrSegmentoPLIng.Enabled = False
            DrProductoIng.Enabled = False
            DrPeriodo.Enabled = False
            TxtUOMIng.Enabled = False

            DrClienteIng.Visible = False
            DrSegmentoPLIng.Visible = False
            LblCustomerING.Visible = False
            lblSegmentPLING.Visible = False

            DrPeriodo.CssClass = ""
            DrClienteIng.CssClass = ""
            DrSegmentoPLIng.CssClass = ""
            DrProductoIng.CssClass = ""
            TxtVolumen.CssClass = ""
            TxtVolumen.Focus()

            TBDetalleForecast.Visible = False
            TBFormIngModForescast.Visible = True

            TxtNombreCliente.Visible = False
            lblNombreCliente.Visible = False

            DrCurrencyUP.Visible = False
            TxtUnitPriceUP.Visible = False
            LblUnitPrice.Visible = False
            DrUOM.Visible = False
            TxtUOMIng.Visible = True
            LblProductName.Visible = False
            TxtProductName.Visible = False

            CalcularPrice(IdCustomer, IdProduct)

        End If
    End Sub



    Protected Sub BtnCancelarForeCast_Click(sender As Object, e As EventArgs) Handles BtnCancelarForeCast.Click
        TBFormIngModForescast.Visible = False

        If Panel1.Visible = False Then
            Cerrar()
        End If

        ' TBDetalleForecast.Visible = True
    End Sub

    Protected Sub ChFiltro_CheckedChanged(sender As Object, e As EventArgs) Handles ChFiltro.CheckedChanged
        If ChFiltro.Checked = True Then
            TBFiltro.Visible = True
        Else
            TBFiltro.Visible = False
        End If
    End Sub

    Protected Sub btnBuscar_Click(sender As Object, e As EventArgs) Handles btnBuscar.Click
        '  CargarProductoDeForecast() -------------------------------OCULTADO
    End Sub

    Protected Sub btnLimpiarB_Click(sender As Object, e As EventArgs) Handles btnLimpiarB.Click
        DrClientesB.SelectedValue = 0
        DrUOMB.SelectedValue = 0
        DrProductoB.SelectedValue = 0
        DrSegmentoPLB.SelectedValue = 0
        DrProductLineB.SelectedValue = 0
        '  txtCodCliente.Text = ""
    End Sub


    Protected Sub DrClienteIng_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DrClienteIng.SelectedIndexChanged
        If DrClienteIng.SelectedValue = 99999999 Then
            TxtNombreCliente.Visible = True
            lblNombreCliente.Visible = True

            DrCurrencyUP.Visible = True
            TxtUnitPriceUP.Visible = True
            LblUnitPrice.Visible = True

        Else
            TxtNombreCliente.Visible = False
            lblNombreCliente.Visible = False

            DrCurrencyUP.Visible = False
            TxtUnitPriceUP.Visible = False
            LblUnitPrice.Visible = False

        End If
        '
        cargarSegmentoPL(0, DrClienteIng.SelectedValue)

        '--- Limpiar productos
        cargarProductos(0, 9999, 0)

    End Sub
    Public Sub cargarSegmentoPL(TipoCarga As Integer, IdCliente As Integer)
        'SegementPL

        If TipoCarga = 1 Then   'MODIFICACION DE FORESCAST

            'SegementPL
            '_servSegmentoPL = New ServSegmentPL()
            'Dim ListSegmentoPL = _servSegmentoPL.SearchSegmentPL(IdCliente, 2013)  '# DEJAR AÑO PARAMETRIZADO
            'DrSegmentoPL.DataTextField = "DesSegmentPL"
            'DrSegmentoPL.DataValueField = "IdSegmentPL"
            'DrSegmentoPL.DataSource = ListSegmentoPL
            'DrSegmentoPL.DataBind()



        Else    ' INGRESO DE NUEVO FORECAST
            _servSegmentoPL = New ServSegmentPL()
            Dim ListSegmentoPL = _servSegmentoPL.SearchSegmentPL(IdCliente, 2013)  '# DEJAR AÑO PARAMETRIZADO
            DrSegmentoPLIng.DataTextField = "DesSegmentPL"
            DrSegmentoPLIng.DataValueField = "IdSegmentPL"
            DrSegmentoPLIng.DataSource = ListSegmentoPL
            DrSegmentoPLIng.DataBind()

            If DrProductoIng.SelectedValue <> "0" Then
                DrProductoIng.SelectedValue = 0
            End If

            '_servServProduct = New ServProduct()
            'TBProducto = _servServProduct.SearchProduct(Usuario.IdEntityF, SegmentoPL)  '# DEJAR AÑO PARAMETRIZADO

            'Session("TBProductoIng") = TBProducto
            'DrProductoIng.DataTextField = "CodDesproduct"
            'DrProductoIng.DataValueField = "IdProduct"
            'DrProductoIng.DataSource = TBProducto
            'DrProductoIng.DataBind()

            'Dim index = DrProductoIng.SelectedIndex
            'If index > -1 Then
            '    TxtUOMIng.Text = TBProducto.Rows(index).Item("DesUOM")
            'End If
        End If


    End Sub

    Protected Sub BtnCancelarGasto_Click(sender As Object, e As EventArgs) Handles BtnCancelarGasto.Click
        Cerrar()

    End Sub

    Protected Sub BtnGuardarForeCast2_Click(sender As Object, e As EventArgs) Handles BtnGuardarForeCast2.Click
        Dim SiError As Boolean
        SiError = ValidarCampos()
        If SiError = True Then
            Exit Sub
        End If

        Dim ModForecast = TransformarForeCast()
        _ServForecast = New ServForecast()
        Dim ExisteForecast = ConsultarForecastExistente() ' _ServForecast.VerificarExistenciaForecast(ModForecast)
        If ExisteForecast.Rows.Count > 0 Then
            If ExisteForecast.Rows(0).Item("IdUsuario") = Usuario.IdUsuario Then
                lblMsgExiste.Text = "El Forecast del Cliente y Producto seleccionado ya fueron ingresados con anterioridad desea abrirlo."
                btnCargarForecastSI.Visible = True
                btncargarForecastNO.Visible = True
            Else
                lblMsgExiste.Text = "El Forecast del Cliente y Producto seleccionado ya fue ingresado por " & ExisteForecast.Rows(0).Item("NameUser")
                btnCargarForecastSI.Visible = False
                btncargarForecastNO.Visible = False
            End If

            MensajeExistencia.Visible = True
            SiError = True
            BtnGuardarForeCast2.Visible = False
            BtnCancelarForeCast.Visible = False
        End If

        If SiError = True Then
            Exit Sub
        End If


        Dim IdCustomer, IdSegment, IdProductLine, IdProduct As Integer

        _ServForecast = New ServForecast()
        _ServForecast.GuardarForecast(ModForecast)
        If ModForecast.IdForecast <> 0 Then
            Session("ActualizarListado") = True
            TBFormIngModForescast.Visible = False
            'Cerrar()

            '-----------------
            IdCustomer = ModForecast.IdCustomer
            IdSegment = ModForecast.IdSegment
            IdProductLine = ModForecast.IdProductLine
            IdProduct = ModForecast.IdProduct

            Dim _BusForecast = CargaParamBusqueda(IdCustomer, IdSegment, IdProductLine)
            CargarProductoDeForecast(_BusForecast)

            CargarForescat(IdCustomer, IdProduct)
            MensajeExistencia.Visible = False

            BtnCancelarForeCast.Visible = True
            lblMensajeIngreso.Visible = True
            '--------------------
        End If
    End Sub

    Private Function CargaParamBusqueda(IdCustomer As Integer, IdSegmento As Integer, IdProductLine As Integer) As BusForecast

        Dim BusForecast = New BusForecast()
        BusForecast.IdCustomer = IdCustomer 'DrClientesB.SelectedValue
        BusForecast.IdUOM = 0 
        BusForecast.IdSegmento = IdSegmento 'DrSegmentoPLB.SelectedValue
        BusForecast.IdProductLine = IdProductLine 'DrProductLineB.SelectedValue
        BusForecast.CodCustomer = "" 'TxtCodClienteB.Text
        Return BusForecast

    End Function
    Private Function ConsultarForecastExistente() As DataTable

        Dim ModForecast = TransformarForeCast()
        _ServForecast = New ServForecast()
        Dim ExisteForecast = _ServForecast.VerificarExistenciaForecast(ModForecast)
        Return ExisteForecast
    End Function
   
    Protected Sub btnCargarForecastSI_Click(sender As Object, e As EventArgs) Handles btnCargarForecastSI.Click
        Dim IdCustomer, IdSegment, IdProductLine, IdProduct As Integer

        Dim ModForecast = TransformarForeCast()
        _ServForecast = New ServForecast()
        Dim ExisteForecast = ConsultarForecastExistente()
        If ExisteForecast.Rows.Count > 0 Then
            IdCustomer = ExisteForecast.Rows(0).Item("IdCustomer")
            IdSegment = ExisteForecast.Rows(0).Item("IdSegment")
            IdProductLine = ExisteForecast.Rows(0).Item("IdProductLine")
            IdProduct = ExisteForecast.Rows(0).Item("IdProduct")

            Dim _BusForecast = CargaParamBusqueda(IdCustomer, IdSegment, IdProductLine)
            CargarProductoDeForecast(_BusForecast)

            CargarForescat(IdCustomer, IdProduct)
            MensajeExistencia.Visible = False

            BtnCancelarForeCast.Visible = True

        End If
    End Sub

    Protected Sub btncargarForecastNO_Click(sender As Object, e As EventArgs) Handles btncargarForecastNO.Click
        MensajeExistencia.Visible = False
        BtnCancelarForeCast.Visible = True

        If Panel1.Visible = True Then
            BtnGuardarForeCast.Visible = True
        Else
            BtnGuardarForeCast2.Visible = True
        End If
    End Sub

 
    Protected Sub btnCalcularPrecio_Click(sender As Object, e As EventArgs) Handles btnCalcularPrecio.Click

        If DrProductoIng.SelectedValue > 0 And DrClienteIng.SelectedValue > 0 Then
            CalcularPrice(DrClienteIng.SelectedValue, DrProductoIng.SelectedValue)
        End If

    End Sub

    Public Function CalcularPrice(IdCustomer, IdProduct)
        Dim InfoPrice As String

        If IsNumeric(TxtVolumen.Text.Trim) Then
            If TxtVolumen.Text.Trim() > 0 Then
                _ServPriceSale = New ServPriceSale
                Dim TBPriceSale = _ServPriceSale.SearchPriceSale(IdCustomer, IdProduct)
                Dim PriceCalculado As String
                PriceCalculado = TxtVolumen.Text * TBPriceSale.Rows(0).Item("Value")
                InfoPrice = "Unit Price: " & TBPriceSale.Rows(0).Item("Value") & " " & TBPriceSale.Rows(0).Item("Currency") & " | Total: " & FormatNumber(PriceCalculado, 2) & " " & TBPriceSale.Rows(0).Item("Currency")

            Else
                InfoPrice = ""
            End If

        Else
            InfoPrice = "Valor debe ser numérico. "
        End If

        lblPrecioCU.Text = InfoPrice
        lblPrecioCU.Visible = True

    End Function
End Class